﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;

namespace JwtDemo.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class AuthController : ControllerBase
    {
        [HttpGet]
        [AllowAnonymous]
        public IActionResult Get(string username, string pwd)
        {
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(pwd))
            {
                Const.ValidAudience = $"{username}{pwd}{DateTime.Now.Millisecond}";
                var claims = new[]
                {
                    new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds()}"),
                    new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddMinutes(5)).ToUnixTimeMilliseconds()}"),
                    new Claim(ClaimTypes.Name, username)
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Const.SecurityKey));
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                var token = new JwtSecurityToken(
                    //颁发者
                    issuer: Const.Domain,
                    //接受者
                    audience: Const.ValidAudience,
                    //自定义参数
                    claims: claims,
                    //过期时间
                    expires: DateTime.Now.AddMinutes(5),
                    //签名证书
                    signingCredentials: creds);

                return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });

            }
            else
            {
                return BadRequest(new { message = "用户和密码不正确1" });
            }
        }

    }
}
